<template>
  <div class="register-container">
    <div class="register-box">
      <div class="role-tabs">
        <div
          class="tab-item"
          :class="{ active: currentRole === 'tourist' }"
          @click="currentRole = 'tourist'"
        >
          <span>游客注册</span>
        </div>
        <div
          class="tab-item"
          :class="{ active: currentRole === 'farmer' }"
          @click="currentRole = 'farmer'"
        >
          <span>农户注册</span>
        </div>
      </div>

      <div class="welcome-text">
        <h2>
          {{
            currentRole === "tourist"
              ? "欢迎注册logos的乡村助农平台"
              : "欢迎加入logos的乡村助农平台"
          }}
        </h2>
        <p>
          {{
            currentRole === "tourist"
              ? "探索乡村魅力，体验自然生活"
              : "展示农产品，拓展销售渠道"
          }}
        </p>
      </div>

      <el-form
        :model="registerForm"
        :rules="rules"
        ref="registerFormRef"
        label-position="top"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <div class="verify-code-container">
            <el-input v-model="registerForm.code" placeholder="请输入验证码" />
            <div class="verify-code-box" @click="handleGetCode">
              <span class="code-text">{{ captchaText || "获取验证码" }}</span>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>

        <el-button
          type="primary"
          class="submit-btn"
          :loading="loading"
          @click="handleRegister"
        >
          立即注册
        </el-button>

        <div class="login-link">
          已有账号？<router-link to="/login">立即登录</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { touristRegister, ruralRegister, getCaptcha } from "@/api/user";
import { setToken } from "@/utils/auth";

const router = useRouter();
const registerFormRef = ref();
const loading = ref(false);
const cooldown = ref(0);
let cooldownTimer: number | null = null;
const currentRole = ref<"tourist" | "farmer">("tourist");
const captchaText = ref(""); // 用于显示验证码

const registerForm = reactive({
  username: "",
  phone: "",
  password: "",
  confirmPassword: "",
  code: "",
});

const validatePass = (rule: any, value: string, callback: Function) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== registerForm.password) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
};

const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, validator: validatePass, trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 1, max: 10, message: "请输入正确的验证码", trigger: "blur" },
  ],
};

const startCooldown = () => {
  cooldown.value = 60;
  cooldownTimer = window.setInterval(() => {
    cooldown.value--;
    if (cooldown.value <= 0 && cooldownTimer) {
      clearInterval(cooldownTimer);
      cooldownTimer = null;
    }
  }, 1000);
};

// 组件卸载时清除定时器
onUnmounted(() => {
  if (cooldownTimer) {
    clearInterval(cooldownTimer);
  }
});

const handleGetCode = async () => {
  try {
    // 先验证手机号
    await registerFormRef.value.validateField("phone");

    // 如果正在倒计时，不允许重复获取
    if (cooldown.value > 0) {
      ElMessage.warning(`请等待${cooldown.value}秒后重试`);
      return;
    }

    const res = await getCaptcha();
    if (res.success) {
      captchaText.value = res.data; // 直接显示后端返回的验证码
      startCooldown(); // 开始倒计时
    } else {
      ElMessage.error(res.message || "获取验证码失败");
    }
  } catch (error: any) {
    ElMessage.error(error.message || "获取验证码失败");
  }
};

const handleRegister = async () => {
  if (!registerFormRef.value) return;

  try {
    await registerFormRef.value.validate();
    loading.value = true;

    const registerData = {
      userName: registerForm.username,
      phone: registerForm.phone,
      password: registerForm.password,
      userType: currentRole.value === "tourist" ? 1 : 2,
      captcha: registerForm.code, // 使用用户输入的验证码
    };

    // 根据用户类型选择不同的注册接口
    const registerApi =
      currentRole.value === "tourist" ? touristRegister : ruralRegister;
    const response = await registerApi(registerData);

    if (response.success) {
      setToken(response.data);
      ElMessage.success("注册成功");
      // 根据用户类型跳转到对应首页
      const targetPath =
        currentRole.value === "tourist" ? "/tourist/home" : "/farmer/home";
      await router.push(targetPath);
    } else {
      throw new Error(response.message || "注册失败");
    }
  } catch (error: any) {
    console.error("注册错误:", error);
    if (error.response) {
      console.error("错误响应详情:", error.response.data);
      ElMessage.error(error.response.data.message || "注册失败");
    } else {
      ElMessage.error(error.message || "注册失败");
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  background: url("@/assets/images/rural-bg.jpg") no-repeat center center fixed;
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 40px;

  .register-box {
    width: 400px;
    margin-right: 60px;
    padding: 30px;
    background: rgba(255, 255, 255, 0.85);
    backdrop-filter: blur(10px);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

    .role-tabs {
      display: flex;
      margin-bottom: 24px;

      .tab-item {
        flex: 1;
        padding: 12px 0;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
        color: #666;

        &.active {
          color: #8bc34a;
          border-bottom: 2px solid #8bc34a;
        }
      }
    }

    .welcome-text {
      text-align: center;
      margin-bottom: 24px;

      h2 {
        font-size: 22px;
        color: #333;
        margin-bottom: 8px;
      }

      p {
        color: #666;
        font-size: 14px;
      }
    }

    .verify-code-container {
      display: flex;
      gap: 12px;

      .el-input {
        flex: 1;
      }

      .verify-code-box {
        min-width: 100px;
        height: 40px;
        background: #e8f5e9;
        border: 1px solid #8bc34a;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s ease;
        padding: 0 15px;

        .code-text {
          font-size: 14px;
          color: #2e7d32;
          font-weight: 500;
          white-space: nowrap;
          letter-spacing: 1px;
        }

        &:hover {
          background: #c8e6c9;
          border-color: #7cb342;
        }

        &:active {
          background: #a5d6a7;
        }
      }
    }

    .submit-btn {
      width: 100%;
      height: 40px;
      margin-top: 20px;
      background: #8bc34a;
      border: none;

      &:hover {
        background: #7cb342;
      }
    }

    .login-link {
      text-align: center;
      margin-top: 16px;
      color: #666;
    }
  }
}
</style> 